<template>
  <Card>
    <Form inline>
      <Row>
        <Col span="22">
          <FormItem label="">
            <DatePicker
              v-model="params.date"
              type="daterange"
              :options="options"
              placeholder="日期选择"
              @on-change="changeDatatime"
            />

            <RadioGroup
              v-model="timeType"
              type="button"
              class="ivu-ml-8"
              @on-change="changeTimeType"
            >
              <Radio label="日" value="1"></Radio>
              <Radio label="周" value="2"></Radio>
              <Radio label="月" value="3"></Radio>
            </RadioGroup>
          </FormItem>
          <FormItem>
            <Input
              v-width="150"
              placeholder="请输入昵称或账号ID"
              v-model="params.keywords"
              @on-clear="searchData"
              @on-enter="searchData"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择项目"
              v-width="120"
              v-model="params.project_id"
              :filterable="projectList.length >= 10"
              @on-open-change="showAll"
              @on-clear="searchData"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in projectList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <TreeSelect
              v-width="150"
              placeholder="部门"
              v-model="params.department_id"
              :data="departmentList"
              @on-change="searchData"
              @on-clear="clearDep"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择平台"
              v-width="120"
              v-model="params.platform_id"
              :filterable="platList.length >= 10"
              @on-open-change="showAll"
              @on-clear="searchData"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in platList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Select
              placeholder="请选择运营人"
              v-width="120"
              v-model="params.use_mid"
              :filterable="principalList.length >= 10"
              @on-open-change="showAll"
              @on-clear="searchData"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in principalList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="2" class="ivu-text-right">
          <Button
            type="primary"
            @click="handleAdd"
            v-hasC="{
              name: 'v1-buss-accounts-consume-create',
              flag: 'v1/buss/accounts-consume/create',
            }"
            >新增投放</Button
          >
        </Col>
      </Row>
    </Form>
    <Table
      :max-height="tableHeigth"
      :columns="columns"
      @on-sort-change="sortChange"
      :data="list"
      :loading="loading"
    >
      <template #hour_minute="{ row }">
        {{ row.hour_minute.substr(0, 5) }}
      </template>
      <template #is_master="{ row }">
        {{ row.is_master == 1 ? "是" : "否" }}
      </template>
      <template #action="{ row }">
        <a
          @click="handleData(row)"
          v-show="row.account_status < 1"
          disabled="true"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update-data',
            flag: 'v1/buss/accounts-consume/update-data',
          }"
          >数据</a
        >
        <a
          @click="handleData(row)"
          v-show="row.account_status > 0"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update-data',
            flag: 'v1/buss/accounts-consume/update-data',
          }"
          >数据</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update-data',
            flag: 'v1/buss/accounts-consume/update-data',
          }"
        />
        <a
          @click="handleEdit(row)"
          v-show="row.account_status < 1"
          disabled="true"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update',
            flag: 'v1/buss/accounts-consume/update',
          }"
          >编辑</a
        >
        <a
          @click="handleEdit(row)"
          v-show="row.account_status > 0"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update',
            flag: 'v1/buss/accounts-consume/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-accounts-consume-update',
            flag: 'v1/buss/accounts-consume/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-buss-accounts-consume-delete',
            flag: 'v1/buss/accounts-consume/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />

    <Modal
      :mask-closable="false"
      v-model="showModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="formInfo" :rules="rules" :label-width="90">
        <FormItem label="账号选择" prop="account_id" required>
          <Select
            placeholder="请选择投流账号"
            v-model="formInfo.account_id"
            :filterable="accountList.length >= 10"
            @on-open-change="showAll"
            clearable
          >
            <Option
              v-for="item in accountList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="日期" prop="date_time" required>
          <DatePicker
            v-model="formInfo.date_time"
            type="date"
            :options="options"
            placeholder="请选择日期"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="金额" prop="money" required>
          <inputNumber
            v-model="formInfo.money"
            type="number"
            :active-change="false"
            :precision="2"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="投放地区" prop="city_id" required>
          <Select
            placeholder="请选择投放地区"
            v-model="formInfo.city_id"
            multiple
            :filterable="cityList.length >= 10"
            clearable
          >
            <Option
              v-for="item in cityList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="时长" prop="hours" required>
          <inputNumber
            v-model="formInfo.hours"
            type="number"
            :max="23"
            :min="1"
            :active-change="false"
            :precision="0"
            placeholder="请输入时长"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="投放类型" prop="type">
          <Select placeholder="投放类型" v-model="formInfo.type" clearable>
            <Option
              v-for="item in typeList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="达人" prop="is_master" required>
          <RadioGroup v-model="formInfo.is_master">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="投放时间" prop="hour_minute" required>
          <TimePicker
            format="HH:mm"
            v-model="formInfo.hour_minute"
            placeholder="投放时间"
            style="width: 100%"
          />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="showModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>

    <Modal
      :mask-closable="false"
      v-model="showDataModal"
      title="数据录入"
      :footer-hide="true"
      :draggable="true"
      :width="360"
    >
      <Form
        ref="consumeData"
        :model="dataInfo"
        :rules="rules"
        :label-width="50"
        inline
      >
        <FormItem label="评论" prop="effective_clue_num" style="width: 46%">
          <inputNumber v-model="dataInfo.effective_clue_num" type="number" />
        </FormItem>
        <FormItem label="私信" prop="private_sms_num" style="width: 46%">
          <inputNumber v-model="dataInfo.private_sms_num" type="number" />
        </FormItem>
        <FormItem label="留电" prop="give_mobile_num" style="width: 46%">
          <inputNumber v-model="dataInfo.give_mobile_num" type="number" />
        </FormItem>
        <FormItem label="推荐" prop="recommend_num" style="width: 46%">
          <inputNumber v-model="dataInfo.recommend_num" type="number" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="showDataModal = false">取消</Button>
        <Button
          type="primary"
          @click="saveData"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import dayjs from "dayjs";
import {
  accountsConsumeList,
  accountsConsumeCreate,
  accountsConsumeUpdate,
  accountsConsumeDataUpdate,
  accountsConsumeDel,
} from "@api/consume.js";
export default {
  name: "consume",
  data() {
    return {
      tableHeigth: document.body.clientHeight - 280,
      loading: false,
      btnLoading: false,
      showModal: false,
      showDataModal: false,
      edit: true,
      timeType: "",
      columns: [
        {
          key: "date_time_str",
          title: "日期",
          width: 110,
          fixed: "left",
        },
        {
          key: "money",
          title: "金额",
          width: 100,
          sortable: "custom",
          fixed: "left",
        },
        {
          key: "city_name",
          title: "投放地区",
          minWidth: 180,
        },
        {
          key: "hours",
          title: "时长",
          width: 80,
          sortable: "custom",
        },
        {
          key: "type_str",
          title: "投放类型",
          width: 110,
        },
        {
          slot: "is_master",
          title: "达人",
          width: 80,
        },
        {
          slot: "hour_minute",
          title: "投放时间",
          width: 100,
        },
        {
          key: "effective_clue_num",
          title: "评论",
          width: 110,
          sortable: "custom",
        },
        {
          key: "private_sms_num",
          title: "私信",
          width: 110,
          sortable: "custom",
        },
        {
          key: "give_mobile_num",
          title: "留电",
          width: 110,
          sortable: "custom",
        },
        {
          key: "recommend_num",
          title: "推荐",
          width: 110,
          sortable: "custom",
        },
        {
          key: "project_name",
          title: "项目",
          width: 100,
        },
        {
          key: "nickname",
          title: "账号昵称",
          width: 200,
        },
        {
          key: "account_name",
          title: "账号ID",
          width: 180,
        },

        {
          key: "platform_name",
          title: "平台",
          width: 120,
        },
        {
          key: "department_name",
          title: "部门",
          width: 110,
        },
        {
          key: "use_mname",
          title: "运营人",
          width: 100,
        },
        {
          slot: "action",
          title: "操作",
          width: 160,
          fixed: "right",
        },
      ],
      list: [],
      total: 0,
      typeList: [],
      cityList: [],
      pageOpts: [10, 20, 30, 40],
      projectList: [],
      principalList: [],
      accountList: [],
      platList: [],
      departmentList: [],
      params: {
        date: [],
        keywords: "",
        project_id: "",
        platform_id: "",
        use_mid: "",
        department_id: "",
        current: 1,
        size: 10,
        order_column: "",
        order_sort: "",
      },
      formInfo: {
        id: "",
        account_id: "",
        money: null,
        date_time: this.$Date().format("YYYY-MM-DD"),
        city_id: "",
        hours: null,
        type: null,
        is_master: 0,
        hour_minute: this.$Date().format("HH:mm"),
      },
      dataInfo: {
        consume_id: "",
        private_sms_num: null,
        effective_clue_num: null,
        give_mobile_num: null,
        recommend_num: null,
      },
      rules: {
        date_time: [{ required: true, message: "请选择日期" }],
        money: [{ required: true, message: "请输入金额" }],
        city_id: [{ required: true, message: "请选择城市" }],
        hours: [{ required: true, message: "请输入时长" }],
        type: [{ required: true, message: "请选择投放类型" }],
        hour_minute: [{ required: true, message: "请选择投放时间" }],
        account_id: [{ required: true, message: "请选择投流账号" }],
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  mounted() {
    this.changeTimeType();
  },
  methods: {
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    changeTimeType() {
      const date = new Date();
      if (this.timeType == "日") {
        this.params.date = [date, date];
      } else if (this.timeType == "周") {
        let week = date.getDay() ? date.getDay() : 7;
        let before = date.getTime() - (week - 1) * 86400 * 1000;
        let beforeDate = new Date(before);
        this.params.date = [beforeDate, date];
      } else if (this.timeType == "月") {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let monthDate = new Date(year + "-" + month + "-1");
        this.params.date = [monthDate, date];
      }
      this.getData();
    },
    changeDatatime() {
      this.timeType = "";
      const date = new Date();

      if (
        dayjs(this.params.date[1]).format("YYYY-MM-DD") ==
        dayjs(date).format("YYYY-MM-DD")
      ) {
        let week = date.getDay() ? date.getDay() : 7;
        let before = date.getTime() - (week - 1) * 86400 * 1000;
        let beforeDate = new Date(before);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let monthDate = new Date(year + "-" + month + "-1");
        if (
          dayjs(this.params.date[0]).format("YYYY-MM-DD") ==
          dayjs(date).format("YYYY-MM-DD")
        ) {
          this.timeType = "日";
        } else if (
          dayjs(this.params.date[0]).format("YYYY-MM-DD") ==
          dayjs(beforeDate).format("YYYY-MM-DD")
        ) {
          this.timeType = "周";
        } else if (
          dayjs(this.params.date[0]).format("YYYY-MM-DD") ==
          dayjs(monthDate).format("YYYY-MM-DD")
        ) {
          this.timeType = "月";
        }
      }
      this.getData();
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    sortChange(e) {
      this.params.order_column = e.key
        ? e.key.replace(/_str$/, "")
        : e.column.slot.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    clearDep() {
      this.params.department_id = "";
      this.searchData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          accountsConsumeDel({ consume_id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      this.showModal = true;
      this.edit = true;
      this.$refs.create.resetFields();
      this.formInfo = {
        id: "",
        account_id: "",
        money: null,
        date_time: this.$Date().format("YYYY-MM-DD"),
        city_id: "",
        hours: null,
        type: null,
        hour_minute: this.$Date().format("HH:mm"),
      };
    },
    handleEdit(row) {
      this.showModal = true;
      this.edit = false;
      this.$refs.create.resetFields();
      this.formInfo = {
        id: row.id,
        account_id: row.account_id,
        money: +row.money,
        date_time: row.date_time_str,
        city_id: row.city_id.split(","),
        hours: +row.hours,
        type: row.type,
        hour_minute: row.hour_minute,
        is_master: +row.is_master,
      };
    },
    editConsumption() {
      this.btnLoading = true;
      if (this.edit) {
        let params = {
          account_id: this.formInfo.account_id,
          money: this.formInfo.money,
          date_time: this.formInfo.date_time,
          city_id: this.formInfo.city_id.join(","),
          hours: this.formInfo.hours,
          type: this.formInfo.type,
          hour_minute: this.formInfo.hour_minute,
          is_master: this.formInfo.is_master,
        };
        accountsConsumeCreate(params)
          .then(() => {
            this.$Message.success("新增成功");
            this.showModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        let params = {
          id: this.formInfo.id,
          account_id: this.formInfo.account_id,
          money: this.formInfo.money,
          date_time: this.formInfo.date_time,
          city_id: this.formInfo.city_id.join(","),
          hours: this.formInfo.hours,
          type: this.formInfo.type,
          hour_minute: this.formInfo.hour_minute,
          is_master: this.formInfo.is_master,
        };
        accountsConsumeUpdate(params)
          .then(() => {
            this.$Message.success("编辑成功");
            this.showModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.editConsumption();
        } else {
          this.showModal = true;
          return;
        }
      });
    },
    handleData(row) {
      this.showDataModal = true;
      this.dataInfo = {
        consume_id: row.id,
        private_sms_num: row.private_sms_num ? +row.private_sms_num : null,
        effective_clue_num: row.effective_clue_num
          ? +row.effective_clue_num
          : null,
        give_mobile_num: row.give_mobile_num ? +row.give_mobile_num : null,
        recommend_num: row.recommend_num ? +row.recommend_num : null,
      };
    },
    saveData() {
      let params = {
        consume_id: this.dataInfo.consume_id,
        private_sms_num: this.dataInfo.private_sms_num,
        effective_clue_num: this.dataInfo.effective_clue_num,
        give_mobile_num: this.dataInfo.give_mobile_num,
        recommend_num: this.dataInfo.recommend_num,
      };
      this.btnLoading = true;
      accountsConsumeDataUpdate(params)
        .then(() => {
          this.btnLoading = false;
          this.$Message.success("编辑成功");
          this.getData();
          this.showDataModal = false;
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    changeData(data) {
      data.forEach((item) => {
        item.value = +item.id;
        item.title = item.department_name;
        item.expand = true;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return data;
    },
    getData() {
      this.loading = true;
      let params = {
        date_stime: this.params.date[0]
          ? dayjs(this.params.date[0]).format("YYYY-MM-DD")
          : "",
        date_etime: this.params.date[1]
          ? dayjs(this.params.date[1]).format("YYYY-MM-DD")
          : "",
        keywords: this.params.keywords,
        project_id: this.params.project_id,
        platform_id: this.params.platform_id,
        use_mid: this.params.use_mid,
        department_id: this.params.department_id,
        page: this.params.current,
        pageSize: this.params.size,
        order_sort: this.params.order_sort,
        order_column: this.params.order_column,
      };
      accountsConsumeList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.cityList = res.condition.city;
          this.typeList = res.condition.type;
          this.projectList = res.condition.project_arr;
          this.platList = res.condition.platform_arr;
          this.principalList = res.condition.principal_member_arr;
          this.accountList = res.condition.account_arr;
          this.departmentList = this.changeData(res.condition.department_arr);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
